package com.thread.book.book2;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

public class AtomicFiled01 {
    public static void main(String[] args) {
        //创建原子更新字段
        AtomicIntegerFieldUpdater<User> atfu = AtomicIntegerFieldUpdater.
                newUpdater(User.class, "age");//原子更新User的 age字段
        // 设置yaozhen20岁
        User yaozhen = new User("yaozhen", 20);
        System.out.println(yaozhen.age);
        //获取旧的字段值并加一:只针对字段
        System.out.println(atfu.getAndIncrement(yaozhen));//20
        // 获取对象字段值,即年龄
        System.out.println(atfu.get(yaozhen));//21

    }

    static class User {
        private String name;
        public volatile int age;//必须用volatile修饰,且为public

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}
